<template>
  <!--  接入规则  -->
  <div class="rule-box">
    <div v-if="$route.query.name || $route.query.id" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <div class="app-container hk-flex-column">
      <div class="app-container-bg">
        <datasourceTypeItem ref="typeItemRef" :tabs="tabs" @handleClick="handleClick" />
      </div>
      <div class="hk-container">
        <div class="hk-flex-bottom">
          <search-form
            :data="queryParams"
            :field-list="searchFieldList"
            :list-type-info="listTypeInfo"
            @handleSearch="handleSearch"
            @handleEvent="handleEvent"
            @handleReset="handleReset"
          />
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button class="el-icon-upload2" size="mini" @click="handleImport">导入 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                :disabled="this.selectionIds.length < 1"
                class="el-icon-download"
                size="mini"
                @click="handleExport"
              >导出
              </el-button>
            </el-col>
          </el-row>
        </div>
        <hk-table
          :loading="loading"
          :table-data="tableList"
          :table-columns="tableLabels"
          :show-index="true"
          :operate="true"
          :selection="true"
          :total="total"
          :table-height="80"
          :query-params="queryParams"
          @changePage="changePage"
          @handleSelectionChange="handleSelectionChange"
        >
          <template #messageType="scope">
            <span>{{ scope.row.messageType=='grok'?'正则解析':'JSON解析' }}</span>
          </template>
          <template #tableList="scope">
            <!-- <div v-for="(i,index) in scope.row.taskNameList " :key="index">{{ i }}</div> -->
            <el-popover v-for="(item, i) in scope.row.taskNameList" :key="i" effect="dark" trigger="hover" placement="top">
              <p>{{ item }}</p>
              <div slot="reference" class="name-wrapper" style="overflow:hidden;text-overflow:ellipsis;white-space: nowrap;">
                {{ item }}
              </div>
            </el-popover>
          </template>
          <template #operate="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">编辑 </el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除 </el-button>
            <el-button size="mini" type="text" @click="handleCopy(scope.row)">复制 </el-button>
          </template>
        </hk-table>

      </div>

      <!--  导入弹出窗  -->
      <file-import ref="fileImportRef" width="600px" :import-data="upload" @importFileSuccess="getList" />
    </div>
  </div>
</template>

<script>
import datasourceTypeItem from './TypeItem'
import FileImport from '@/components/FileImport/index.vue'
import { treeselect } from '@/api/milkyway/accessProduct'
import searchForm from '@/components/HkSearchform/index.vue'
import HkTable from '@/components/Hk-Table/index.vue'
import { getList, getMetaDataList, delRulePolicy, ruleDownLoad, copyRulePolicy } from '@/api/milkyway/accessRules'
import { ProductType } from '@/api/milkyway/gatherData'
export default {
  name: 'MlkAccessRule',
  components: { searchForm, HkTable, FileImport, datasourceTypeItem },
  beforeRouteLeave(to, from, next) {
    if (to.path.includes('/mlk/access/rule/ruleAdd' || to.path.includes('/mlk/access/rule/ruleAdd/add'))) {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
    }
    next()
  },
  data() {
    return {
      tabs: [
        { name: '全部规则',
          num: 0,
          code: null
        }
      ],
      // 左侧树默认选项
      defaultId: this.$route.query.id ? [this.$route.query.id] : ['0'],

      // 产品类型列表
      productOptions: [],
      currentKey: this.$route.query.id || '0',

      formData: {},
      // 搜索配置项
      searchFieldList: [
        {
          label: '关键字',
          type: 'input',
          field: 'ruleName',
          placeholder: '请输入规则名称',
          maxlength: 40
        },
        /* {
          label: '接入产品',
          type: 'cascader',
          field: 'productCode',
          list: 'productCodeList',
          props: {
            value: 'id',
            label: 'name',
            checkStrictly: true,
            multiple: false
          }
        }, */
        {
          label: '元数据',
          type: 'select',
          field: 'metaDataId',
          list: 'metaDataIdList'
        },
        //  解析模式参数字段未确定
        {
          label: '解析模式',
          type: 'select',
          field: 'messageType',
          list: 'messageTypeList'
        }
      ],
      listTypeInfo: {
        metaDataIdList: [],
        productCodeList: [],
        messageTypeList: [{ value: 'grok', label: '正则解析' }, { value: 'json', label: 'JSON解析' }]
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 表格配置
      tableLabels: [
        { label: '规则名称', param: 'name' },
        { label: '解析模式', param: 'messageType', type: 'slot' },
        { label: '接入产品', param: 'productName' },
        { label: '元数据', param: 'metaDataName' },
        { label: '关联任务', param: 'tableList', type: 'slot', showToolTip: true }
      ],
      // 弹出层标题
      title: '',
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        ruleName: undefined,
        metaDataId: undefined
      },
      code: this.$route.query.id,
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      upload: {
        // 是否更新已经存在的用户数据
        updateSupport: false,
        // 设置上传的请求头部
        // headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        // 上传的地址
        url: window.baseUrl.mlk + '/rulePolicy/ruleUpload'
      },
      selectionIds: []
    }
  },
  activated() {
    this.getList()
  },
  async mounted() {
    this.$route.meta.keepAlive = true
    await this.getTreeselect()
    // 获取元数据下拉框
    await this.getMetaDataList()
    await this.getProuductType()
    // this.getList()
  },
  methods: {
    // tabs 点击回调
    handleClick(index, item) {
      if (index === 0) {
        this.code = null
      } else {
        this.code = item.code
      }
      this.queryParams.current = 1
      this.getList()
    },
    /** 获取产品类型 */
    getProuductType() {
      ProductType(0).then((res) => {
        const resVal = res
        if (resVal.length > 0) {
          resVal.forEach((item) => {
            item.children.forEach((i) => {
              delete i.children
            })
          })
        }
        this.listTypeInfo.productCodeList = resVal
      })
    },
    /** 获取元数据下拉框 */
    getMetaDataList() {
      getMetaDataList().then((res) => {
        const lists = res.map((item) => {
          return { label: item.mdName, value: item.id }
        })
        this.listTypeInfo.metaDataIdList = lists
      })
    },
    /** 查询事件 **/
    handleSearch(data) {
      this.queryParams = data
      this.queryParams.current = 1
      let productCode = null
      if (this.queryParams.productCode) {
        if (this.queryParams.productCode.length > 1) {
          productCode = this.queryParams.productCode[1]
        } else {
          productCode = this.queryParams.productCode[0]
        }
      }
      this.getList({ 'productCode': productCode })
    },
    /** 触发搜索表单变化 */
    handleEvent(obj) {
      this.queryParams[obj.field] = obj.value
    },
    /** 重置按钮事件 */
    handleReset(data) {
      this.queryParams = data
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.getList()
    },
    /** 查询产品类型树结构 */
    getTreeselect() {
      treeselect({ type: 'rule' }).then((res) => {
        this.tabs = [
          { name: '全部规则',
            num: 0,
            code: null
          }
        ]
        const arr = []
        if (res.length > 0) {
          this.tabs[0].num = res[0].num
          res[0].children.forEach(item => {
            const Arr = item.children.map(i => {
              return { name: i.name, num: i?.num || 0, code: i.id }
            })
            arr.push(...Arr)
          })
          this.tabs.push(...arr)
          this.productOptions = res
          this.tabs.sort((a, b) => {
            return b.num - a.num
          }

          )
        }
        if (this.$route.query.id) {
          this.tabs.forEach((i, index) => {
            if (i.code == this.$route.query.id) {
              this.$refs.typeItemRef.activeIndex = index
              this.handleClick(index, i)
            }
          })
        } else {
          this.getList()
        }
      })
    },
    /** 查询列表 */
    getList(param) {
      this.loading = true
      getList(Object.assign({ code: this.code }, this.queryParams, param)).then((res) => {
        this.tableList = res.list
        this.total = res.total
        this.loading = false
      })
    },
    /** 表格操作事件 **/
    handleSelectionChange(data) {
      if (data.length > 0) {
        this.selectionIds = data.map((item) => {
          return item.id
        })
      } else {
        this.selectionIds = []
      }
    },
    // 表单重置
    reset() {
      (this.menuExpand = false),
      (this.menuNodeAll = false),
      (this.deptExpand = true),
      (this.deptNodeAll = false),
      (this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: '0',
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined
      })
      this.resetForm('form')
    },
    /** 新增按钮操作 */
    handleAdd() {
      const id = 'add'
      this.$store.commit('ruleParsing/CLEANDIALOGECHODATA')
      this.$store.commit('ruleParsing/CHANGECLEAN')
      this.$router.push({
        path: window.prefix + '/mlk/access/rule/ruleAdd/' + id,
        query: {
          title: '接入规范'
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.formData = row
      this.reset()
      this.$store.commit('ruleParsing/CLEANDIALOGECHODATA')
      this.$store.commit('ruleParsing/CHANGECLEAN')
      this.title = '编辑'
      this.$router.push({
        path: window.prefix + '/mlk/access/rule/ruleAdd/' + row.id,
        query: {
          title: '接入规范'
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name = row.name
      this.$modal
        .confirm('是否确认删除此项数据？')
        .then(function() {
          return delRulePolicy(row.id)
        })
        .then((res) => {
          const totalPage = Math.ceil((this.total - 1) / this.queryParams.size)
          this.queryParams.current = this.queryParams.current > totalPage ? totalPage : this.queryParams.current
          this.getList()
          this.getTreeselect()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 复制按钮 */
    handleCopy(row) {
      this.$modal
        .confirm('是否确认复制此行数据项？')
        .then(function() {
          return copyRulePolicy({ id: row.id })
        }).then(res => {
          this.$message.success('复制成功')
          this.getList()
        })
    },
    /** 左树点击事件*/
    handleNodeClick(data) {
      if (data.id == 0) {
        this.code = undefined
      } else {
        this.code = data.id
      }
      this.queryParams.current = 1
      this.getList()
    },
    /** 点击分页事件*/
    changePage(param) {
      this.queryParams.current = param.current
      this.queryParams.size = param.size
      let productCode = null
      if (this.queryParams.productCode) {
        if (this.queryParams.productCode.length > 1) {
          productCode = this.queryParams.productCode[1]
        } else {
          productCode = this.queryParams.productCode[0]
        }
      }
      this.getList({ 'productCode': productCode })
    },
    /** 导出按钮操作 */
    handleExport() {
      const ids = this.selectionIds.join(',')
      this.gDownload(
        window.baseUrl.mlk + '/rulePolicy/ruleDownLoad',
        { ids: ids },
        `accessRules_${new Date().getTime()}.zip`
      )
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.fileImportRef.show()
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table{
  margin-top:0 !important;
}
::v-deep .content{
  padding:0 !important;
  flex:1;
}
.el-tree,
.el-tree-node {
  width: 100% !important;
  height: 100% !important;
  overflow: auto;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  width: fit-content;
  min-width: 100%;
  width:100%;
}
.hk-container {
    background: #fff;
    width: 100% !important;
    overflow: hidden;
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
    border-radius: 4px;
  }
.app-container {
  padding:0px !important;
  width:100%;
  overflow: hidden !important;
  background:#eef0f5 !important;

}
.el-tag-custom {
  max-width: 85%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
